package socket;
/**
 * 聊天室的客户端 版本4
 * v3V版本的客户端start方法中主要
 */

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client4 {
    private Socket socket;

    public Client4() {
        try {
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost", 8088);
            System.out.println("服务器已连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            //V4:启动用于接收服务器消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            //低级流，作用：将写出的字节发送给建立连接的远程计算机
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);//按行写入和自动行刷新

            Scanner scan = new Scanner(System.in);
            while (true) {
                String line = scan.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();//与服务器断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client4 client = new Client4();
        client.start();
    }

    //V4：该线程任务是负责不断接收来自服务端发送过来的消息并输出到控制台
    private class ServerHandler implements Runnable {
        public void run() {
            try {
                //通过socket获取输入流用于读取来自服务端发送过来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
